package com.example.demo.controller;

import com.example.demo.model.Student;
import com.example.demo.model.Major;
import com.example.demo.model.Classes;
import com.example.demo.service.StudentService;
import com.example.demo.service.UserService;
import com.example.demo.service.ImportService;
import com.example.demo.service.MajorService;
import com.example.demo.service.ClassService;
import com.example.demo.util.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/api/students")
@CrossOrigin(origins = "http://localhost:5173") // 允许前端访问
public class StudentController {
    
    private static final Logger logger = LoggerFactory.getLogger(StudentController.class);
    
    @Autowired
    private StudentService studentService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private ImportService importService;
    
    @Autowired
    private MajorService majorService;
    
    @Autowired
    private ClassService classService;

    // 获取所有学生
    @GetMapping
    public Page<Student> getAllStudents(@RequestParam(required = false) String studentNo,
                                       @RequestParam(required = false) String name,
                                       @RequestParam(defaultValue = "0") int page,
                                       @RequestParam(defaultValue = "10") int size) {
        if (studentNo != null || name != null) {
            return studentService.searchStudents(studentNo, name, page, size);
        }
        return studentService.getAllStudents(page, size);
    }

    // 根据ID获取学生
    @GetMapping("/{id}")
    public ResponseEntity<Student> getStudentById(@PathVariable Long id) {
        Optional<Student> student = studentService.getStudentById(id);
        if (student.isPresent()) {
            return ResponseEntity.ok(student.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 创建学生
    @PostMapping
    public ResponseEntity<?> createStudent(@Valid @RequestBody Student student) {
        try {
            logger.info("Received student data for creation: {}", student);
            
            // 验证学院、专业、班级的关联关系
            ResponseEntity<?> validationResponse = validateCollegeMajorClassRelation(student);
            if (validationResponse != null) {
                return validationResponse;
            }
            
            Student savedStudent = studentService.saveStudent(student);
            logger.info("Student created successfully with ID: {}", savedStudent.getId());
            return ResponseEntity.ok(savedStudent);
        } catch (Exception e) {
            logger.error("Error creating student: ", e);
            return ResponseEntity.badRequest().body("创建学生失败: " + e.getMessage());
        }
    }

    // 更新学生
    @PutMapping("/{id}")
    public ResponseEntity<?> updateStudent(@PathVariable Long id, @Valid @RequestBody Student studentDetails) {
        try {
            logger.info("Received student data for update (ID: {}): {}", id, studentDetails);
            
            // 验证学院、专业、班级的关联关系
            ResponseEntity<?> validationResponse = validateCollegeMajorClassRelation(studentDetails);
            if (validationResponse != null) {
                return validationResponse;
            }
            
            Optional<Student> student = studentService.getStudentById(id);
            if (student.isPresent()) {
                Student updatedStudent = student.get();
                updatedStudent.setUserId(studentDetails.getUserId());
                updatedStudent.setStudentNo(studentDetails.getStudentNo());
                updatedStudent.setCollegeId(studentDetails.getCollegeId());
                updatedStudent.setMajorId(studentDetails.getMajorId());
                updatedStudent.setClassId(studentDetails.getClassId());
                updatedStudent.setEnrollmentYear(studentDetails.getEnrollmentYear());
                studentService.saveStudent(updatedStudent);
                logger.info("Student updated successfully with ID: {}", updatedStudent.getId());
                return ResponseEntity.ok(updatedStudent);
            } else {
                logger.warn("Student not found for update with ID: {}", id);
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.error("Error updating student: ", e);
            return ResponseEntity.badRequest().body("更新学生失败: " + e.getMessage());
        }
    }

    // 删除学生
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteStudent(@PathVariable Long id) {
        Optional<Student> student = studentService.getStudentById(id);
        if (student.isPresent()) {
            // 先删除学生记录
            studentService.deleteStudent(id);
            // 再删除对应的用户记录
            userService.deleteUser(student.get().getUserId());
            logger.info("Student and corresponding user deleted successfully with ID: {}", id);
            return ResponseEntity.ok().build();
        } else {
            logger.warn("Student not found for deletion with ID: {}", id);
            return ResponseEntity.notFound().build();
        }
    }

    // 根据学号获取学生
    @GetMapping("/studentNo/{studentNo}")
    public ResponseEntity<Student> getStudentByStudentNo(@PathVariable String studentNo) {
        Optional<Student> student = studentService.getStudentByStudentNo(studentNo);
        if (student.isPresent()) {
            return ResponseEntity.ok(student.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 根据用户ID获取学生
    @GetMapping("/user/{userId}")
    public ResponseEntity<Student> getStudentByUserId(@PathVariable Long userId) {
        Optional<Student> student = studentService.getStudentByUserId(userId);
        if (student.isPresent()) {
            return ResponseEntity.ok(student.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    // 根据班级ID获取学生列表
    @GetMapping("/class/{classId}")
    public ResponseEntity<List<Student>> getStudentsByClassId(@PathVariable Long classId) {
        List<Student> students = studentService.getStudentsByClassId(classId);
        return ResponseEntity.ok(students);
    }
    
    // 导出所有学生列表
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportAllStudents() {
        try {
            // 获取所有学生
            List<Student> students = studentService.getAllStudentsForExport();
            
            // 导出为Excel
            byte[] excelData = ExcelUtils.exportStudentsToExcel(students, "所有学生");
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "学生列表.xlsx");
            
            return new ResponseEntity<>(excelData, headers, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("导出学生列表失败: ", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    // 根据班级ID导出学生列表
    @GetMapping("/class/{classId}/export")
    public ResponseEntity<byte[]> exportStudentsByClassId(@PathVariable Long classId) {
        try {
            // 获取班级信息
            Optional<Classes> classOpt = classService.getClassById(classId);
            if (!classOpt.isPresent()) {
                return ResponseEntity.notFound().build();
            }
            
            Classes classInfo = classOpt.get();
            
            // 获取学生列表
            List<Student> students = studentService.getStudentsByClassId(classId);
            
            // 导出为Excel
            byte[] excelData = ExcelUtils.exportStudentsToExcel(students, classInfo.getName());
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "班级_" + classInfo.getName() + "_学生列表.xlsx");
            
            return new ResponseEntity<>(excelData, headers, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("导出学生列表失败: ", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    // 下载学生导入模板
    @GetMapping("/template")
    public ResponseEntity<byte[]> downloadStudentTemplate() {
        try {
            byte[] template = ExcelUtils.createStudentTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "学生导入模板.xlsx");
            return new ResponseEntity<>(template, headers, HttpStatus.OK);
        } catch (IOException e) {
            logger.error("下载学生导入模板失败: ", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    // 导入学生数据
    @PostMapping("/import")
    public ResponseEntity<String> importStudents(@RequestParam("file") MultipartFile file) {
        try {
            String result = importService.importStudents(file);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("导入学生数据失败: ", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("导入失败: " + e.getMessage());
        }
    }
    
    // 验证学院、专业、班级的关联关系
    private ResponseEntity<?> validateCollegeMajorClassRelation(Student student) {
        // 验证学院、专业、班级ID是否有效
        if (student.getCollegeId() == null) {
            return ResponseEntity.badRequest().body("请选择学院");
        }
        
        if (student.getMajorId() == null) {
            return ResponseEntity.badRequest().body("请选择专业");
        }
        
        if (student.getClassId() == null) {
            return ResponseEntity.badRequest().body("请选择班级");
        }
        
        // 验证专业是否属于该学院
        Optional<Major> majorOpt = majorService.getMajorById(student.getMajorId());
        if (!majorOpt.isPresent() || !majorOpt.get().getCollegeId().equals(student.getCollegeId())) {
            return ResponseEntity.badRequest().body("选择的专业不属于该学院");
        }
        
        // 验证班级是否属于该专业
        Optional<Classes> classOpt = classService.getClassById(student.getClassId());
        if (!classOpt.isPresent() || !classOpt.get().getMajorId().equals(student.getMajorId())) {
            return ResponseEntity.badRequest().body("选择的班级不属于该专业");
        }
        
        return null; // 验证通过
    }
}